﻿namespace OpenAIProxy;

// 配置文件模型
public record ProviderConfig(
    string Name,
    string Endpoint,
    string ApiKey,
    string ApiVersion,
    Dictionary<string, ModelConfig> Models
);

public record ModelConfig(
    string Name,
    decimal CostPerToken,
    bool StreamSupported,
    int MaxTokens
);

// 高级配置管理服务
public class ConfigManager
{
    private readonly IConfiguration _config;
    private List<ProviderConfig>? _providers;

    public ConfigManager(IConfiguration config)
    {
        _config = config;
    }

    public List<ProviderConfig> GetProviders()
    {
        if (_providers != null) return _providers;
        
        _providers = new List<ProviderConfig>();
        var providerSection = _config.GetSection("OpenAIProviders");
        
        foreach (var providerItem in providerSection.GetChildren())
        {
            var models = new Dictionary<string, ModelConfig>();
            var modelSection = providerItem.GetSection("Models");
            
            foreach (var modelItem in modelSection.GetChildren())
            {
                models[modelItem["Name"]!] = new ModelConfig(
                    Name: modelItem["Name"]!,
                    CostPerToken: decimal.Parse(modelItem["CostPerToken"]!),
                    StreamSupported: bool.Parse(modelItem["StreamSupported"]!),
                    MaxTokens: int.Parse(modelItem["MaxTokens"]!)
                );
            }
            
            _providers.Add(new ProviderConfig(
                Name: providerItem["Name"]!,
                Endpoint: providerItem["Endpoint"]!,
                ApiKey: providerItem["ApiKey"]!,
                ApiVersion: providerItem["ApiVersion"]!,
                Models: models
            ));
        }
        
        return _providers;
    }

    public ProviderConfig? GetProviderConfig(string name)
    {
        return GetProviders().FirstOrDefault(p => p.Name == name);
    }

    public ModelConfig? GetModelConfig(string provider, string model)
    {
        return null;

        // return GetProviders()
        //     .FirstOrDefault(p => p.Name == provider)?
        //     .Models.TryGetValue(model, out var config) 
        //         ? config : null;
    }
}
